package javabase.desginpattern.structure.proxy.cglibdynamicproxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author fance
 * @date 18-4-27 下午4:44
 */
public class CGLibProxy implements MethodInterceptor{

    private Enhancer enhancer = new Enhancer();

    public Object getProxy(Class clazz){
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        before();
        Object res = methodProxy.invokeSuper(o,objects);
        after();
        return res;
    }

    private void before() {
        System.out.println("before");
    }
    private void after() {
        System.out.println("after");
    }

    public static void main(String[] args) {
        CGLibProxy cgLibProxy = new CGLibProxy();
        FanceSay proxy = (FanceSay) cgLibProxy.getProxy(FanceSay.class);
        proxy.say();
    }
}
